const express = require('express');
const cors = require('cors');
const http = require('http');
const mongoose = require('mongoose');
const path = require('path');
require('dotenv').config();

const app = express();
const server = http.createServer(app);

// MongoDB连接配置
const mongooseOptions = {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    serverSelectionTimeoutMS: 10000,
    socketTimeoutMS: 45000,
    family: 4,
    retryWrites: true
};

// 连接数据库并添加重试机制
const connectWithRetry = () => {
    console.log('正在尝试连接MongoDB...');
    mongoose.connect(process.env.MONGODB_URI, mongooseOptions)
        .then(() => {
            console.log('MongoDB 连接成功');
        })
        .catch(err => {
            console.error('MongoDB 连接失败:', err);
            console.log('5秒后重试连接...');
            setTimeout(connectWithRetry, 5000);
        });
};

// 监听MongoDB连接事件
mongoose.connection.on('connected', () => {
    console.log('Mongoose 已连接');
});

mongoose.connection.on('error', (err) => {
    console.error('Mongoose 连接错误:', err);
});

mongoose.connection.on('disconnected', () => {
    console.log('Mongoose 连接断开，尝试重新连接...');
    connectWithRetry();
});

process.on('SIGINT', async () => {
    await mongoose.connection.close();
    process.exit(0);
});

connectWithRetry();

// 中间件
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));
app.use(express.static(path.join(__dirname, '../../public')));

// 路由
app.use('/api', require('./routes/auth'));
app.use('/api', require('./routes/canvas'));
app.use('/api', require('./routes/user'));

// API 路由
app.get('/api/health', (req, res) => {
    const dbStatus = mongoose.connection.readyState === 1 ? 'connected' : 'disconnected';
    const serverStatus = {
        status: 'ok',
        timestamp: new Date().toISOString(),
        database: {
            status: dbStatus,
            host: process.env.MONGODB_URI ? new URL(process.env.MONGODB_URI).hostname : 'unknown'
        },
        uptime: process.uptime()
    };

    if (dbStatus !== 'connected') {
        serverStatus.status = 'degraded';
    }

    res.json(serverStatus);
});

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error('错误详情:', err);

    // 处理MongoDB错误
    if (err.name === 'MongoError' || err.name === 'MongoServerError') {
        return res.status(500).json({
            success: false,
            message: '数据库操作失败',
            error: process.env.NODE_ENV === 'development' ? err.message : undefined
        });
    }

    // 处理验证错误
    if (err.name === 'ValidationError') {
        return res.status(400).json({
            success: false,
            message: '数据验证失败',
            error: process.env.NODE_ENV === 'development' ? err.message : undefined
        });
    }

    // 处理JWT错误
    if (err.name === 'JsonWebTokenError' || err.name === 'TokenExpiredError') {
        return res.status(401).json({
            success: false,
            message: '认证失败',
            error: process.env.NODE_ENV === 'development' ? err.message : undefined
        });
    }

    // 处理其他错误
    const statusCode = err.statusCode || 500;
    const message = err.message || '服务器内部错误';

    res.status(statusCode).json({
        success: false,
        message: message,
        error: process.env.NODE_ENV === 'development' ? {
            stack: err.stack,
            name: err.name
        } : undefined
    });
});

const PORT = process.env.PORT || 3001;
server.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
});